<template>
<div>
  <el-dialog
    title="同步字典"
    :close-on-click-modal="false"
    :visible.sync="visible">
     <json-viewer :value="jsonData" :expand-depth="4" copyable sort></json-viewer>
    <span slot="footer" class="dialog-footer">
      <el-button @click="refresh">刷新</el-button>
      <el-button type="primary" @click="doSubmit()" v-noMoreClick :loading="loading">确定</el-button>
    </span>
  </el-dialog>
</div>
</template>

<script>
  import JsonViewer from 'vue-json-viewer'
  export default {
    data () {
      return {
        visible: false,
        loading: false,
        content: ''
      }
    },
    components: {
      JsonViewer
    },
    computed: {
      jsonData: {
        get () {
          if(this.content === '' || !this.content.startsWith("{")){
            return {}
          }
          return JSON.parse(this.content)
        }
      }
    },
    methods: {
      init () {
        this.visible = true
        this.refresh();
      },
      refresh() {
        var self = this;
        navigator.clipboard
        .readText()
        .then((v) => {
          self.content =  v
        })
        .catch((v) => {
          this.$message.error('获取剪贴板内容失败');
        });
      },
      // 表单提交
      doSubmit () {
        if(this.content === "" || !this.content.startsWith("{")) {
          this.$message.error('JSON格式内容不正确');
          return;
        }
        this.loading = true
        this.$http({
          url: `/sys/dict/saveJson`,
          method: 'post',
          data: {
            jsonData: this.content
          }
        }).then(({data}) => {
          if (data && data.success) {
            this.$message.success(data.msg)
            this.visible = false
            this.$emit('refreshDataList')
          }
          this.loading = false
        })
      }
    }
  }
</script>
